// index page
// ============

define(['require', 'zepto', 'utils', 'wx', 'ejs', 'wxpay', 'sui'], function(require, $, utils, wx, ejs, wxpay) {
  return {
    init: function(data) {
      this.unionid=data.unionid
      this.modal = {
      }
      utils.configWeixin(data.jsConfig, false);
      this.showRules = data.showRules;
      this.requestData(data);
      this.initPage();
      this.initPicker();
      this.submitForm();
      this.headerHtml = '<a href="javascript:void(0);" class="item-content shopping-content">\
    	            <% if(product.id != 1) {%>\
                    <div class="item-media" style="<%= product.single_avatar == true ? "width: 6.8rem; display: block;" : "" %>">\
    	              <% if(product.single_avatar == false) {%>\
                      <img src="'+window.__CTX__.resource+'<%=product.coach_avatar%>.jpg?v=0.01" style="width: 6.8rem;">\
                      <% } else { %>\
                       <% product.coach_avatar_list.forEach(function(imageItem){%>\
                         <img src="'+window.__CTX__.resource+'<%=imageItem%>.jpg?v=0.01" style="width: 6rem; margin-bottom: .3rem;">\
                       <% }) %>\
                       <% } %>\
                    </div>\
                    <% } %>\
                    <div class="item-inner <%=product.id == 1 ? "no-pic" : "" %>" style="margin-left: .5rem;">\
                      <div class="item-title-row">\
                        <div class="item-title"><%=product.name%></div>\
                      </div>\
                      <div class="item-subtitle">\
                        <div class="">课程导师：\
                        <% product.coach_name_list.forEach(function(name, index){%>\
                        <%= index == 0 ? "" : "&" %> <%=name%>\
                        <% }) %>\
                        </div>\
                        <div class="">上课时间：<%=product.occur_time%></div>\
                      </div>\
                      <div class="item-text" style="height: 3rem;">\
                        <div><%=product.id == 1 ? "精英" : "" %>装备包</div>\
                        <div><%=product.equipment_package%></div>\
                      </div>\
                    </div>\
                  </a>';
      
      this.hasMobileHtml = '<li class="item-content">\
                             <div class="item-media">\
                               <i class="iconfont icon-mobile-phone"></i>\
                             </div>\
                             <div class="item-inner" style="padding-right: 1.5rem;">\
                               <div class="item-title">绑定手机</div>\
                               <div class="item-after">\
                                 <%=user.mobile%>\
                                 <input type="hidden" name="mobile" value="<%=user.mobile%>" />\
                               </div>\
                             </div>\
                           </li>';
      
      this.bindMobileHtml = '<li>\
                              <a href='+window.__CTX__.root+'/bind-mobile?sku=<%=product.id%> class="item-content item-link">\
                              <div class="item-media">\
                                <i class="iconfont icon-mobile-phone"></i>\
                              </div>\
                              <div class="item-inner" style="padding-right: 1.5rem;">\
                                <div class="item-title">绑定手机</div>\
                                <div class="item-after">请绑定手机</div>\
                              </div>\
                              </a>\
                            </li>';
      
      this.userInfoHtml = '<ul class="user-info">\
                            <li class="user-cover"><i class="iconfont icon-user"></i></li>\
                            <li>\
                              <div class="item-content">\
                                <div class="item-inner" style="padding-right: 1.5rem;">\
                                  <div class="item-title label">姓名</div>\
                                  <div class="item-input">\
                                    <input type="text" placeholder="请输入姓名" name="name" value="<%=userInfo.name%>" >\
                                  </div>\
                                </div>\
                              </div>\
                            </li>\
                            <li>\
                              <div class="item-content item-link">\
                                <div class="item-inner">\
                                  <div class="item-title label">性别</div>\
                                  <div class="item-input">\
                                    <input name="gender" type="text" id="gender-picker" class="<%=courseSize > 0 ? "disabled" : ""%>" value="<%=userInfo.gender%>" <%=courseSize > 0 ? "readonly" : ""%> />\
                                    <input type="hidden" value="<%=userInfo.gender == "男" ? "MALE" : "FEMALE"%>">\
                                  </div>\
                                </div>\
                              </div>\
                            </li>\
                            <li>\
                              <div class="item-content item-link">\
                                <div class="item-inner">\
                                  <div class="item-title label">年龄</div>\
                                  <div class="item-input">\
                                    <input name="age" type="text" id="age-picker" class="<%=courseSize > 0 ? "disabled" : ""%>" value="<%=userInfo.age%>" <%=courseSize > 0 ? "readonly" : ""%> />\
                                  </div>\
                                </div>\
                              </div>\
                            </li>\
                          </ul>';
      
      this.malePickerHtml = '<ul>\
                              <li>\
                              <div class="item-content item-link">\
                                <div class="item-media">\
                                  <i class="iconfont icon-cotta"></i>\
                                </div>\
                                <div class="item-inner">\
                                  <div class="item-title label">短袖尺码</div>\
                                  <div class="item-input">\
                                    <input name="maleClothesSize" type="text" id="male-cotta-picker" value="<%=userInfo.clothes_size%>" />\
                                  </div>\
                                </div>\
                              </div>\
                            </li>\
                            <% if (product.id == 1) { %>\
                            <li>\
                              <div class="item-content item-link">\
                                <div class="item-media">\
                                  <i class="iconfont icon-shoes"></i>\
                                </div>\
                                <div class="item-inner">\
                                  <div class="item-title label">鞋子尺码</div>\
                                  <div class="item-input">\
                                    <input name="maleShoeSize" type="text" id="male-shoes-picker" class="<%=courseSize > 0 ? "disabled" : ""%>" value="<%=userInfo.shoe_size%>" <%=courseSize > 0 ? "readonly" : ""%> />\
                                  </div>\
                                </div>\
                              </div>\
                            </li>\
                            <% } %>\
                          </ul>';
      
      this.femalePickerHtml = '<ul>\
                              <li>\
                              <div class="item-content item-link">\
                                <div class="item-media">\
                                  <i class="iconfont icon-cotta"></i>\
                                </div>\
                                <div class="item-inner">\
                                  <div class="item-title label">短袖尺码</div>\
                                  <div class="item-input">\
                                    <input name="femaleClothesSize" type="text" id="female-cotta-picker" value="<%=userInfo.clothes_size%>" />\
                                  </div>\
                                </div>\
                              </div>\
                            </li>\
                            <% if (product.id == 1) { %>\
                            <li>\
                              <div class="item-content item-link">\
                                <div class="item-media">\
                                  <i class="iconfont icon-shoes"></i>\
                                </div>\
                                <div class="item-inner">\
                                  <div class="item-title label">鞋子尺码</div>\
                                  <div class="item-input">\
                                    <input name="femaleShoeSize" type="text" id="female-shoes-picker" class="<%=courseSize > 0 ? "disabled" : ""%>" value="<%=userInfo.shoe_size%>" <%=courseSize > 0 ? "readonly" : ""%> />\
                                  </div>\
                                </div>\
                              </div>\
                            </li>\
                            <% } %>\
                          </ul>';
      
    },
    
    requestData: function(data) {
      var that = this;
      $.ajax({
        type : 'GET',
        url : window.__CTX__.domain + '/api/products/' + data.sku,
        dataType : 'json',
        timeout : 30000,
        success : function(res) {
          console.log(res);
          if(res.code == 0) {
              that.product = res.data.product
              var headerResult = ejs.render(that.headerHtml, {product : that.product})
              $('.product-info').html(headerResult);
              var price = (parseInt(that.product.price) / 100).toFixed(2);
              $(".product-price").html(price)
              $.ajax({
                  type : 'GET',
                  url : window.__CTX__.domain + '/api/profile?unionid=' + that.unionid,
                  dataType : 'json',
                  timeout : 30000,
                  success : function(res) {
                    console.log(res);
                    if(res.code == 0) {
                        that.user = res.data.user
                        that.userInfo = res.data.userInfo
                        that.courseSize = res.data.courseSize
                        
                        var userInfoResult = ejs.render(that.userInfoHtml, {userInfo : that.userInfo, courseSize: that.courseSize})
                        if(that.user.mobile) {
                          var mobileResult = ejs.render(that.hasMobileHtml, {user : that.user})
                          $('.mobile').html(mobileResult);
                        }else {
                          var mobileResult = ejs.render(that.bindMobileHtml, {user : that.user, product: that.product})
                          $('.mobile').html(mobileResult);
                        }
                        
                        $(".user-info-div").html(userInfoResult);
                        that.initPicker();

                        if(that.userInfo.gender == "男") {
                          var pickerResult = ejs.render(that.malePickerHtml, {userInfo : that.userInfo, product: that.product, courseSize: that.courseSize})
                          $('.male-size-list').css("display", "block").html(pickerResult);
                          that._bindPicker("男");
                        } else if (that.userInfo.gender == "女") {
                           var pickerResult = ejs.render(that.femalePickerHtml, {userInfo : that.userInfo, product: that.product, courseSize: that.courseSize})
                            $('.female-size-list').css("display", "block").html(pickerResult);
                            that._bindPicker("女");
                        }
                        
                        
                        
                    } else {
                      $.toast("获取用户信息失败");
                    } 
                  },
                  error : function(xhr, type) {
                    alert('Ajax error!')
                  }
                })
          } else {
            $.toast("获取课程数据失败");
          } 
        },
        error : function(xhr, type) {
          alert('Ajax error!')
        }
      })
    },
    initPage: function() {
      var count = 10;
      var that = this;
      
      if(that.showRules == "false") {

        $(".agree-button").css("display", "none");
        $(".bug-button").css("display", "block");
        $(".agreement-content").css("display", "none");
        $(".payment-content").css("display", "block");

      } else {

        this.modal.timerId = setInterval(function() {
          count--;
          if(count<=0) {
            clearInterval(that.modal.timerId);
//            $(".agree-button").css("display", "none");
//            $(".bug-button").css("display", "block");
//            $(".agreement-content").css("display", "none");
//            $(".payment-content").css("display", "block");
            $(".count-down").html('')
            $(".agree-button").removeClass("disabled");
            
          } else {
            $(".count-down").html(count)
          }
          
      }, 1000)
      
      
      $(document).on("click", ".agree-button", function() {
        if(!$(this).hasClass("disabled")) {
          clearInterval(that.modal.timerId);
          $(".agree-button").css("display", "none");
          $(".bug-button").css("display", "block");
          $(".agreement-content").css("display", "none");
          $(".payment-content").css("display", "block");
        }
      })
      }
    },
    
    generateData: function() {
      
    },
    
    initPicker: function() {
      var that = this;
      if(!$("#gender-picker").hasClass('disabled')) {
        $("#gender-picker").picker({
          toolbarTemplate: '<header class="bar bar-nav">\
            <button class="button button-link pull-right close-picker">确定</button>\
            <h1 class="title">选择性别</h1>\
            </header>',
            cols: [
              {
                textAlign: 'center',
                values: ['MALE', 'FEMALE'],
                displayValues: ['男', '女']
              }
            ],
            
            onClose: function() {
              that._bindPicker($("#gender-picker").val());
            },

            formatValue: function (picker, value, displayValue){
              $(this.input).next().val(value)
              return displayValue
            }
          });
      }
      
      if(!$("#age-picker").hasClass('disabled')) {
          
        $("#age-picker").picker({
          toolbarTemplate: '<header class="bar bar-nav">\
          <button class="button button-link pull-right close-picker">确定</button>\
          <h1 class="title">选择年龄</h1>\
          </header>',
          value: ['18'],
          cols: [
            {
              textAlign: 'center',
              values: ['18', '19', '20',
                       '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40',
                       '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60'],
            }
          ],
        });
      }
          
          
    },
    _bindPicker: function(gender) {
      var that = this;
      if(gender == '女') {
        if(!$("#female-cotta-picker").hasClass('disabled')) {
          $(".female-size-list").css("display", "block");
          $(".male-size-list").css("display", "none")
          $("#female-cotta-picker").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
            <button class="button button-link pull-right close-picker">确定</button>\
            <h1 class="title">选择尺码</h1>\
            </header>',
            cols: [
              {
                textAlign: 'center',
                values: ['XS', 'S', 'M', 'L', 'XL'],
              }
            ]
          });
        }
        
        if(!$("#female-shoes-picker").hasClass('disabled')) {
          $("#female-shoes-picker").picker({
          toolbarTemplate: '<header class="bar bar-nav">\
          <button class="button button-link pull-right close-picker">确定</button>\
          <h1 class="title">选择鞋码</h1>\
          </header>',
          cols: [
            {
              textAlign: 'center',
              values: ['35.5', '36', '36.5', '37.5', '38', '38.5', '39', '40', '40.5', '41', '42', '43'],
            }
          ]
        });
        }
      } else if(gender == '男') {
        if(!$("#male-cotta-picker").hasClass('disabled')) {
          $(".female-size-list").css("display", "none");
          $(".male-size-list").css("display", "block");
          
          $("#male-cotta-picker").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
            <button class="button button-link pull-right close-picker">确定</button>\
            <h1 class="title">选择尺码</h1>\
            </header>',
            cols: [
              {
                textAlign: 'center',
                values: ['S', 'M', 'L', 'XL', 'XXL', '3XL'],
              }
            ]
          });
        }
        
        if(!$("#male-shoes-picker").hasClass('disabled')) {
          $("#male-shoes-picker").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
            <button class="button button-link pull-right close-picker">确定</button>\
            <h1 class="title">选择鞋码</h1>\
            </header>',
            cols: [
              {
                textAlign: 'center',
                values: ['40', '40.5', '41', '42', '42.5', '43', '44', '44.5', '45', '45.5', '46', '47', '47.5', '48', '48.5'],
              }
            ]
          });
        }
        
      }
      
    },

    submitForm: function () {
      var that = this;
      $(document).on('click', "a.bug-button", function(event) {
        event.preventDefault();
        var submiting = that._submitForm();
        $.when(submiting).done(function(data){
          that.configWxPay(data)
        });
        
      });
    },

    _submitForm : function() {
      var that = this;

      var mobileValue = $("input[name='mobile']").length > 0 ? $("input[name='mobile']").val() : null;
      var nameValue = $("input[name='name']").val();
      var genderValue = $("input[name='gender']").val();
      var ageValue = $("input[name='age']").val();

      if(!mobileValue) {
        $.toast("请绑定手机号");
        return;
      }

      if(!nameValue) {
        $.toast("请和输入姓名");
        return;
      }

      if(!genderValue) {
        $.toast("请选择性别");
        return;
      }

      if(!ageValue) {
        $.toast("请选择年龄");
        return;
      }

      var showSizeValue = null;
      var clothesSizeValue = null;

      if(genderValue == '男') {
        showSizeValue = $("input[name='maleShoeSize']").length > 0 ? $("input[name='maleShoeSize']").val() : null;
        clothesSizeValue = $("input[name='maleClothesSize']").val();
      } else if(genderValue == '女') {
        showSizeValue = $("input[name='femaleShoeSize']").length > 0 ? $("input[name='femaleShoeSize']").val() : null;
        clothesSizeValue = $("input[name='femaleClothesSize']").val();
      }

      if(!showSizeValue && that.product.id == 1) {
         $.toast("请选择鞋子尺码");
         return;
      }

      if(!clothesSizeValue) {
        $.toast("请选择短袖尺码");
        return;
      }

      console.log("开始发送请求")

      var that = this, defer = $.Deferred()
      $.showPreloader('正在提交支付数据')
      $.ajax({
        url: window.__CTX__.root + '/api/orders?unionid=' + that.unionid,
        type: 'POST',
        data: {
        'name': nameValue,
        'productId': that.product.id,
        'gender': genderValue,
        'age': ageValue,
        'clothesSize': clothesSizeValue,
        'shoeSize': showSizeValue
        }
      })
      .done(function(response) {
        utils.processResult(response, function(result) {
          defer.resolve(result.data)
        }, function(result) {
          if(response.code == "600") {
            $.hidePreloader()
            $.toast(result.message || '该课程报名已满')
            window.location.href= window.__CTX__.root + "/shopping/empty"
          } else {
            $.hidePreloader()
            $.toast(result.message || '请求支付数据失败')
            setTimeout(function() {
              window.location.reload();
            }, 1000);
          }
        })
      })
      .fail(function() {
        console.log("error");
      });
        
      return defer.promise()
    },

    /**
     * Handle success WeChat pay, config WeChat JS SDK and invoke pay
     */
    configWxPay: function(result) {
      
      
      var that = this,
          jsConfig = result.jsConfig,
          order = result.order;
      
      var submiting = that.requestPayConfig(order);
      $.when(submiting).done(function(data, order) {
        wxpay.injectConfig(data.jsConfig, ['chooseWXPay'])
        wxpay.invokePay(data.payConfig, function(res) {
          setTimeout(function() {
              window.location.href= window.__CTX__.root + "/shopping/" + order.id + "/result";
          }, 1000)
        })
      })
    },

    requestPayConfig: function(order) {
      var that = this, defer = $.Deferred()
      $.post(window.__CTX__.root + '/api/payments/pay', {
        'orderId': order.id,
        'unionid': that.unionid,
        'currentUrl': window.location.href
       }).done(function(response) {
          utils.processResult(response, function(result) {
            $.hidePreloader()
            defer.resolve(result.data, order)
          }, function(result) {
            if(response.code == "600") {
              $.hidePreloader()
              $.toast(result.message || '该课程报名已满')
              window.location.href= window.__CTX__.root + "/shopping/empty"
            } else {
              $.hidePreloader()
              $.toast(result.message || '请求支付数据失败')
              setTimeout(function() {
                window.location.reload();
              }, 1000);
            }
          })
        })
        
      return defer.promise()
    }
  }
})